<?php
namespace App\HttpController;
use EasySwoole\EasySwoole\Swoole\Task\TaskManager;
use think\Db;
use EasySwoole\Validate\Validate;
use App\Lib\Redis\Redis;
use App\Model\User as UserModel;
use App\Model\FriendGroup as FriendGroupModel;
use App\Model\GroupMember as GroupMemberModel;
use EasySwoole\VerifyCode\Conf;
use App\Lib\Upload\Image;
use App\Lib\Upload\Video;
use App\HttpController\Base;
class Index extends Base{
    public function index()
    {
        $token =  $this->params['token'];


        $user = Redis::getInstance()->get('User_token_'.$token);

        if (!$user) {
            $this->response()->redirect("/index/login");
        }
        $user = json_decode($user,true);
        $hostName = 'ws://easy.haozhuanapp.com:9501';
        $this->fetch('index',[
            'server' => $hostName,
            'token'=>$token,
            'user'=>$user
        ]);

    }

    public function login() {
        if($this->request()->getMethod() == 'POST') {
            //用户登陆聊天系统
            $validate = new Validate();
            $validate->addColumn('username')->required('用户名必填');
            $validate->addColumn('password')->required('密码必填');
            if ($this->validate($validate)) {
                $user = Db::table('user')->where('username','eq',$this->params['username'])->find();
                if(!$user) {
                    return $this->writeJson(10001,'用户不存在');
                }
                if ($this->setpass($this->params['password'])!=$user['password']) {
                    return $this->writeJson(10001,'密码输入不正确!');
                }
                $token = uniqid().uniqid().$user['id'];
                //异步存储该用户信息到redis当中
                TaskManager::async(function() use($token,$user){
                    Redis::getInstance()->set('User_token_'.$token,json_encode($user),36000);
                });
                return $this->writeJson(200,['token'=>$token],'登录成功');
            } else {
                $this->writeJson(10001,$validate->getError()->__toString(),'login fail');
            }
        } else {
            $this->fetch('login');
        }

    }
    public function register() {
        if ($this->request()->getMethod() == 'POST') {
            $validate = new Validate();
            $validate->addColumn('username')->required('用户名必填');
            $validate->addColumn('password')->required('密码必填');
            $validate->addColumn('nickname')->required('昵称必填');
            $validate->addColumn('code')->required('验证码必填');

            $codeCache = Redis::getInstance()->get('Code'.$this->params['key']);

            if ($codeCache != $this->params['code']){
                return $this->writeJson(10001, '验证码错误',$codeCache);
            }

            $UserModel = new UserModel();
            $user = Db::table('user')->where('username','eq',$this->params['username'])->find();
            if ($user) {
                return $this->writeJson(10001,'用户名已存在');
            }
            $data = [
                'avatar' => $this->params['avatar'],
                'nickname' => $this->params['nickname'],
                'username' => $this->params['username'],
                'password' => $this->setpass($this->params['password']),
                'sign' => $this->params['sign'],
            ];

            $user_id = Db::table('user')->insertGetId($data);
            if (!$user_id) {
                return $this->writeJson(10001, '注册失败');
            }


            Db::table('friend_group')->insert([
                'user_id' => $user_id,
                'groupname' => '默认分组'
            ]);


            Db::table('group_member')->insert([
                'user_id' => $user_id,
                'group_id' => 10001
            ]);


            return $this->writeJson(200, '注册成功');

        } else {
            $code_hash = uniqid().uniqid();
            $this->fetch('register',[
                'code_hash'=>$code_hash
            ]);
        }
    }

    /**
     * 验证码
     */
    public function getCode(){

        $key = $this->params['key'];

        $config = new Conf();
        $code = new \EasySwoole\VerifyCode\VerifyCode($config);
        $num = mt_rand(000,999);
        TaskManager::async(function() use($key,$num){
            Redis::getInstance()->set('Code'.$key,$num,1000);
        });
        $this->response()->withHeader('Content-Type','image/png');
        $this->response()->write($code->DrawCode($num)->getImageByte());
    }
    //图片上传
    public function upload() {
        $request = $this->request();
        try {
            $obj = new Image($request);
            $file = $obj->upload();
        } catch (\Exception $e) {
            return $this->writeJson(400,[],$e->getMessage());
        }
        if (empty($file)) {
            return $this->writeJson(400,[],'上传失败');
        }
        $data = [
            'url' => '/webroot'.$file
        ];
        return $this->writeJson(200,$data,'ok');
    }
    //聊天图片上传
    public function messageUpload() {
        $request = $this->request();
        try {
            $obj = new Image($request);
            $file = $obj->upload();
        } catch (\Exception $e) {
            return $this->writeJson(400,[],$e->getMessage());
        }
        if (empty($file)) {
            return $this->writeJson(400,[],'上传失败');
        }
        $data = [
            'src' => 'http://easy.haozhuanapp.com:9501/webroot'.$file
        ];
        return $this->writeDataJson(0,$data,'ok');
    }
    //聊天文件上传
    public function messageFile() {
        $request = $this->request();
        try {
            $obj = new Video($request);
            $file = $obj->upload();
        } catch (\Exception $e) {
            return $this->writeDataJson(400,[],$e->getMessage());
        }
        if (empty($file)) {
            return $this->writeDataJson(400,[],'上传失败');
        }
        $data = [
            'src' => 'http://easy.haozhuanapp.com:9501/webroot'.$file,
            'name'=>$obj->getFileName()
        ];
        return $this->writeDataJson(0,$data,'ok');
    }
    /*
    * 获取房间
    * */
    function room(){
        $res = Db::table('wl_room')->select();
        return $this->writeJson(200,$res,'ok');
    }
    public function ce() {
        $res = Db::table('user')->select();
        $this->writeJson(200,$res);
    }
    public function intoRoom() {
        $this->fetch('room');
    }
}